//
//  SystemSelectPhotoManager.m
//  PhotoManager
//
//  Created by Coollang on 2017/9/1.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "SystemSelectPhotoManager.h"
#import "MBProgressHUD+HudTools.h"
#import <objc/runtime.h>
#import <objc/message.h>

#define arcWitch [UIScreen mainScreen].bounds.size.width/2

@interface SystemSelectPhotoManager ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, assign) BOOL canEdit;

@property (nonatomic, strong) UIViewController *presentController;
/** 图片选择完成的回调 */
@property (nonatomic, copy) SelecteImageCallBlock callBlock;
@end

@implementation SystemSelectPhotoManager

+ (instancetype)selectPhotoManagerWithEditCaseType:(kPhotoEditCaseType)type {
    SystemSelectPhotoManager *manager = [[SystemSelectPhotoManager alloc] init];
    manager.editCaseType = type;
    return manager;
}

- (void)takePhotoBySource:(NSInteger)soureType canEdit:(BOOL)edit parentViewController:(UIViewController *)controller selectCallBlock:(SelecteImageCallBlock)callBlock {
    self.canEdit = edit;
    self.presentController = controller;
    self.callBlock = callBlock;
    (soureType % 2) ? [self takePhotoByPhotos]:[self takePhotoByCamera];
}

- (void)takePhotoByCamera {
    
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Can't get camera or photo information", nil) inView:self.presentController.view];
        if (self.callBlock) {
            NSError *error = [[NSError alloc] initWithDomain:@"打开相机失败" code:-101 userInfo:nil];
            self.callBlock(nil,error);
            self.callBlock = nil;
        }
        return;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.delegate = self;
    
    [picker setAllowsEditing:YES];
    [self.presentController presentViewController:picker animated:YES completion:nil];
}

- (void)takePhotoByPhotos {
    
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Can't get camera or photo information", nil) inView:self.presentController.view];
        if (self.callBlock) {
            NSError *error = [[NSError alloc] initWithDomain:@"打开相册失败" code:-102 userInfo:nil];
            self.callBlock(nil,error);
            self.callBlock = nil;
        }
        return;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    [picker setAllowsEditing:YES];
    
    [self.presentController presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIImagePickerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    
    if (self.canEdit) {
        image = [info objectForKey:UIImagePickerControllerEditedImage];
    }
    UIImage *image2 = image;
    
//    if (self.needCutImage) {
//        if (self.imageCutRect.size.width != 0 && self.imageCutRect.size.height != 0) {
//            image2 = [UIImage imagewithOriginImage:image2 cutSize:self.imageCutRect];
//        }else {
//            if (self.editCaseType == kPhotoEditCircel) {
//                // 裁剪图片成圆形
//                image2 = [UIImage imagewithImage:image];
//                image2 = [self resizedImageWithBounds:CGSizeMake(image2.size.width, image2.size.height) originImage:image2];
//            }else {
//                image2 = [self resizedImageWithBounds:CGSizeMake(image2.size.width, image2.size.height) originImage:image2];
//            }
//        }
//    }
    if (self.callBlock) {
        self.callBlock(image2,nil);
        self.callBlock = nil;
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    // iOS11 系统不支持下面的操作
//    if (navigationController.viewControllers.count == 3 && self.canEdit && _editCaseType != kSystemDeflaut)
//    {
//        UIPageViewController *curImageVc = navigationController.viewControllers[2];
//        curImageVc.title = @"Move and scale";
//        Method method = class_getInstanceMethod([self class], @selector(drawRect:));
//        NSArray *subVuews = [[navigationController viewControllers][2].view subviews];
//        class_replaceMethod([[[[navigationController viewControllers][2].view subviews][1] subviews][0] class],@selector(drawRect:),method_getImplementation(method),method_getTypeEncoding(method));
//    }
}




- (void)dealloc {
    NSLog(@"SystemSelectPhotoManagerDealloc");
}
/*
-(void)drawRect:(CGRect)rect
{
    CGContextRef ref = UIGraphicsGetCurrentContext();
    CGContextAddRect(ref, rect);
    
    CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
    
    if (_editCaseType == kPhotoEditRectangle) {
          CGContextAddRect(ref, CGRectMake(0, (screenH -  screenW),  screenW,  screenW));
    }else if (_editCaseType == kPhotoEditCircel){
         CGContextAddArc(ref, screenW/2, screenH/2, arcWitch, 0, M_PI*2, NO);
    }
    [[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]setFill];
    CGContextDrawPath(ref, kCGPathEOFill);
    
    if (_editCaseType == kPhotoEditRectangle) {
        CGContextAddRect(ref, CGRectMake(0, (screenH -  screenW),  screenW,  screenW));
    }else if (_editCaseType == kPhotoEditCircel){
        CGContextAddArc(ref, screenW/2, screenH/2, arcWitch, 0, M_PI*2, NO);
    }
    [[UIColor whiteColor]setStroke];
    CGContextStrokePath(ref);
}
*/

- (UIImage *)resizedImageWithBounds:(CGSize)bounds originImage:(UIImage *)originImage
{
    CGFloat horizontalRatio = bounds.width / originImage.size.width;
    CGFloat verticalRatio = bounds.height / originImage.size.height;
    CGFloat ratio = MIN(horizontalRatio, verticalRatio);
    CGSize newSize = CGSizeMake(originImage.size.width * ratio, originImage.size.height * ratio);
    UIGraphicsBeginImageContextWithOptions(newSize, YES, 0);
    [originImage drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

@end
